// xc_lshop/shop/deposit/send/index.js
var actmemberbill = require('../../../../xc/model/member')
var actdepositbill = require('../../model/deposit_bill')

Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    depositconfig: null,
    form: {
      uid:"",
      shoppronum: 0,
      shoppros: {},
      customerpronum: 0,
      customerpros: []
    }
  },
  getmember(uid) {
    var that = this;
    actmemberbill.getmember(uid).then(res => {
      if (res["status"] == 1) {
        that.setData({
          member: res['obj']
        })
      } else {
        that.error(res['message'])
      }
    })
  },
  valide() {
    var customerpros = this.data.form.customerpros
    var message = "请完善您要寄存的商品信息后上传或者将未完善的商品数量减至0";
    var status = true;
    if (customerpros.length > 0) {
      for (var i in customerpros) {
        if ((!customerpros[i]['simg']) || (!customerpros[i]['name'])) {
          status = false;
          break;
        }
      }
    }
    if (!status) {
      wx.showModal({
        title: "错误",
        content: message
      })
    }



    console.log(customerpros)
    return status
  },
  //提交订单
  comfirmdeposit() {
    var that = this;
    var rest = that.valide();
    if (rest) {
      wx.showModal({
        title: "提示",
        content: "确认寄存？",
        success(res) {
          if (res.confirm) {
            var model=that.data.form
            that.postorder(model)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }

        

        },fail(){

        }

      })
    }

  },
  //提交订单
  postorder(ordermodel) {
    var that = this;
    if(that.data.depositid){
      ordermodel['depositid']=that.data.depositid
    }
    actdepositbill.createorder(ordermodel).then(function (res) {
      if (res["status"] == 1) {
        if(that.data.operator=='user'){
          var obj=res["obj"]
          that.selectComponent("#qrcode").init(1,obj)
       
        }else{
          that.setData({
            'order.status':2,
          })
          wx.showModal({
            title:"寄存成功",
            content:"寄存成功,是否重新扫码？",
            confirmText: '重新扫码',
            cancelText:'返回首页',
            success (res) {
              if (res.confirm) {
                wx.scanCode({
                  success (res) {
                    console.log(res)
                  }
                })
              
              } else if (res.cancel) {
                wx.redirectTo({
                  url: '/xc_lshop/index/index',
                })
              }
            }
          })
        }
        
        
      } else {
        wx.showModal({
          title: '错误',
          content: res["message"],
        })
      }
    })
  },
  afterlogin: function (options, config, userinfo) {
    var that = this;
    var update = {}
    update['form.uid']=options.uid

    if (userinfo['member_id'] != 0) {
      if (options.uid == userinfo['member_id'] && userinfo.memberinfo.authority != 2) {
        update['member'] = userinfo
        update['operator'] = 'user'
      } else {
        update['operator'] = 'manager'
        if (userinfo.memberinfo.authority == 2) {
          update['manager'] = userinfo
          this.getmember(options.uid)
          if(options.depositid){
            update['depositid'] = options.depositid
            this.getorder(options.depositid)
          }
        } else {
          that.error("抱歉，只有管理员才可以操作", true)
        }

      }
    }
    this.setData(
      update
    )
  },
  getorder(id){
    var that = this;
    actdepositbill.getorder(id).then(res => {
      if (res["status"] == 1) {
        
        if (res['obj'].status != 1) {
          var statusname = "已拒绝"
          if (res['obj'].status == 2) {
            statusname = "已取件"
          }
          wx.showModal({
            title: "提示",
            content: "该订单" + statusname + ",是否重新取件？",
            confirmText: '重新取件',
            cancelText: '返回首页',
            success(res) {
              if (res.confirm) {
               

              } else if (res.cancel) {
                wx.redirectTo({
                  url: '/xc_lshop/index/index',
                })
              }
            }
          })
        }else{
          that.setData({
            order:res['obj'],
            form: res['obj']['contents']
          })
        }
      } else {
        that.error(res['message'])
      }
    })
  },
  //显示商家产品
  showshoppro() {

    this.selectComponent("#prolist").init(this.data.depositconfig, this.data.form.shoppros)

  },
  //增加顾客产品
  addcustomerpro() {
    var list = this.data.form.customerpros;
    var item = {
      name: "",
      simg: "",
      num: 1,
      fileList: []
    }
    list.push(item);
    this.setData({
      'form.customerpros': list
    })
    this.computenum('customerpronum')
  },
  //商家产品确认选择
  comfirm(e) {
    var pros = e.detail
    this.setData({
      'form.shoppros': pros
    })
    this.computenum('shoppronum')
  },
  computenum(key) {
    var list = "";
    if (key == 'shoppronum') {
      list = this.data.form.shoppros
    } else {
      list = this.data.form.customerpros
    }
    var num = 0
    for (var i in list) {
      if (list[i].num > 0) {
        num += list[i].num * 1
      }
    }
    this.setData({
      ['form.' + key]: num
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
  },
  //options {uid=67}
  xcloaddata: function (options, config) {
    if (config.deposit && config.deposit.status == 1) {
      this.setData({
        depositconfig: config.deposit
      })
    } else {
      this.error("寄存功能未开启", true)
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onNameChange(e) {
    var index = e.currentTarget.dataset.index;
    console.log("wx.createInnerAudioContext()")
    console.log(index)

    this.setData({
      ['form.customerpros[' + index + '].name']: e.detail.value
    })
  },
  oncustomproChange(e) {
    var index = e.currentTarget.dataset.index;
    var num = e.detail;
    var custompro = this.data.form.customerpros
    if (num > 0) {
      custompro[index].num = num
    } else {
      custompro.splice(index, 1)
    }
    console.log("custompro")
    console.log(custompro)
    this.setData({
      ['form.customerpros']: custompro
    })
    this.computenum('customerpronum')
  },
  //商家-单属性计步器
  onChange(e) {
    var chooselists = this.data.form.shoppros
    var num = e.detail;
    var id = e.currentTarget.dataset.id;
    if (num > 0) {
      chooselists[id]['num'] = num
    } else {
      delete chooselists[id]
    }
    console.log("chooselists")
    console.log(chooselists)
    this.setData({
      'form.shoppros': chooselists
    })
    this.computenum("shoppronum")
  },
  //商家-多规格计步器
  onGuigeChange(e) {
    var dataset = e.currentTarget.dataset
    var chooselists = this.data.form.shoppros
    // var modellistitem=this.data.modellists[dataset.index]
    var num = e.detail
    // if(chooselists[modellistitem['id']]){ //存在
    var modellistitem = chooselists[dataset['id']]
    modellistitem['skudata']['stockdata'][dataset.cartesidx]['num'] = num
    // }
    var stockdata = modellistitem['skudata']['stockdata'];
    var allnum = 0
    for (var i in stockdata) {
      if (stockdata[i]['num'] > 0) {

        allnum += stockdata[i]['num'] * 1
      }
    }
    if (allnum > 0) {
      modellistitem['num'] = allnum
      chooselists[modellistitem['id']] = modellistitem

    } else {
      delete chooselists[modellistitem['id']]
    }
    this.setData({
      'form.shoppros': chooselists
    })
    this.computenum("shoppronum")


  },
  //上传图片
  afterRead(event) {
    console.log("event")
    console.log(event)
    var dataset = event.currentTarget.dataset
    var that = this
    const {
      file
    } = event.detail
    if (file.constructor == Array) {
      file.forEach(item => {
        that.savefilefunc(item, dataset.idx)
      })
    } else {
      that.savefilefunc(file, dataset.idx)
    }
  },
  //删除图片
  deleteImg(e) {

    var that = this;
    var idx = e.currentTarget.dataset.idx;
    console.log("idx")
    console.log(idx)

    // var fileList = that.data.fileList
    // var index = e.detail.index;

    // fileList[idx].splice(index, 1);

    this.setData({
      ['form.customerpros[' + idx + '].simg']: "",
      ['form.customerpros[' + idx + '].fileList']: [],

    });
    // var imglist = [];
    // fileList[idx].forEach(item => {
    //   imglist.push(item.url)
    // })
    // console.log("imglist")
    // console.log(imglist)
    // that.data.xcmodel[idx].imglist = imglist

  },
  //上传图片-2
  uploadimg(file, idx) {
    var app = getApp()

    var that = this
    app.toolv2.uploadFile(file.path).then(function (item) {


      var fileList = that.data.form.customerpros[idx].fileList;
      fileList.push({
        ...file,
        url: item.obj.fullpath
      });
      console.log("fileList")
      console.log(fileList)

      // that.data.fileList[idx] = fileList
      console.log("item")
      console.log(item)
      var updatemodel = {}
      updatemodel['form.customerpros[' + idx + '].simg'] = fileList[0]['url']
      updatemodel['form.customerpros[' + idx + '].fileList'] = fileList

      // updatemodel["fileList"] = that.data.fileList
      // var imglist = [];
      // fileList.forEach(item => {
      //   imglist.push(item.url)
      // })
      // that.data.xcmodel[idx].imglist = imglist
      that.setData(updatemodel)

    })
  },
  //上传-1
  savefilefunc(file, idx) {

    console.log("file")
    console.log(file)

    if (file.path) {
      this.uploadimg(file, idx)
    } else {
      for (var i in file) {
        this.uploadimg(file[i], idx)
      }
    }


  },
})